package com.xdjd.mobile.business.util;

import com.xdjd.mobile.business.util.init.MethodSource;
import com.xdjd.mobile.business.util.init.ServiceApi;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zxl on 2017-12-08
 **/
@Component
public class SpringContextUtils implements ApplicationContextAware {
    private static ApplicationContext ctx;
    public static Map<MethodSource, Object> methodMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        ctx = arg0;
    }

    public static Object getBean(String beanName) {
        return ctx.getBean(beanName);
    }

    public static <T> T getBean(Class<T> clazz) {
        return ctx.getBean(clazz);
    }

    public static void getApiBeanMap() {
        String[] beanNames = ctx.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            Class<?> type = ctx.getType(beanName);
            ServiceApi annotation = type.getDeclaredAnnotation(ServiceApi.class);
            if (annotation == null) {
                continue;
            }
            Method[] methods = type.getDeclaredMethods();
            for (Method method : methods) {
                ServiceApi serviceApi = method.getDeclaredAnnotation(ServiceApi.class);
                if (serviceApi == null) {
                    continue;
                }
                methodMap.put(serviceApi.value(), method);
            }
        }
    }

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }
}
